// content.js
(() => {
  // 默认每 10 分钟检查一次（单位 ms）
  const DEFAULT_INTERVAL_MS = 10 * 60 * 1000;

  let checkInterval = null;
  let intervalMs = DEFAULT_INTERVAL_MS;
  let currentVideo = null;
  let pendingCheckIn = false;

  // helper: 是否在播放
  function isVideoPlaying(video) {
    if (!video) return false;
    return !!(
      video.currentTime > 0 &&
      !video.paused &&
      !video.ended &&
      video.readyState > 2
    );
  }

  // 尝试找到页面中的 video 元素
  function findVideo() {
    const vids = document.querySelectorAll("video");
    if (!vids || vids.length === 0) return null;
    // 选择第一个可用的 video（可根据需要改进）
    for (const v of vids) {
      if (v.tagName.toLowerCase() === "video") return v;
    }
    return vids[0] || null;
  }

  // 向扩展后台发消息（video 暂停）
  function notifyBackgroundPaused(reason) {
    chrome.runtime.sendMessage({
      type: "video_paused",
      url: location.href,
      title: document.title,
      reason: reason || null,
      time: Date.now(),
    });
  }

  // 定期检查
  function startIntervalCheck(ms) {
    stopIntervalCheck();
    intervalMs = ms || DEFAULT_INTERVAL_MS;
    checkInterval = setInterval(() => {
      currentVideo = currentVideo || findVideo();
      const playing = isVideoPlaying(currentVideo);
      console.log(
        "[video-monitor] interval check playing:",
        playing,
        "url:",
        location.href
      );
      if (!playing) {
        // video 停止——可能弹窗或浏览器策略
        notifyBackgroundPaused("interval_check");
      }
    }, intervalMs);
    console.log("[video-monitor] started periodic check:", intervalMs, "ms");
  }

  function stopIntervalCheck() {
    if (checkInterval) {
      clearInterval(checkInterval);
      checkInterval = null;
    }
  }

  // 侦测 visibilitychange
  document.addEventListener("visibilitychange", () => {
    console.log("[video-monitor] visibilitychange: hidden?", document.hidden);
    chrome.runtime.sendMessage({
      type: "visibility_change",
      hidden: document.hidden,
      url: location.href,
      time: Date.now(),
    });
  });

  // 监听 video 的 pause 事件（如果视频被暂停会触发）
  function attachVideoListeners(video) {
    if (!video) return;
    video.addEventListener("pause", () => {
      console.log("[video-monitor] video.pause event");
      notifyBackgroundPaused("video_pause_event");
    });

    video.addEventListener("play", () => {
      console.log("[video-monitor] video.play event");
      chrome.runtime.sendMessage({
        type: "video_played",
        url: location.href,
        time: Date.now(),
      });
    });
  }

  // 监听页面上新加的 video（如播放器后加载）
  const mo = new MutationObserver((mutations) => {
    for (const m of mutations) {
      if (m.addedNodes && m.addedNodes.length) {
        for (const node of m.addedNodes) {
          if (node.tagName && node.tagName.toLowerCase() === "video") {
            console.log(
              "[video-monitor] new video added to DOM, attaching listeners"
            );
            currentVideo = node;
            attachVideoListeners(currentVideo);
          } else if (node.querySelectorAll) {
            const vids = node.querySelectorAll("video");
            if (vids.length) {
              currentVideo = vids[0];
              attachVideoListeners(currentVideo);
            }
          }
        }
      }
    }
  });
  mo.observe(document.documentElement || document.body, {
    childList: true,
    subtree: true,
  });

  // 初始化
  (async function init() {
    currentVideo = findVideo();
    if (currentVideo) attachVideoListeners(currentVideo);

    // 从扩展存储读取用户设置的间隔（ms）
    chrome.storage.sync.get(
      { checkIntervalMs: DEFAULT_INTERVAL_MS },
      (items) => {
        startIntervalCheck(items.checkIntervalMs || DEFAULT_INTERVAL_MS);
      }
    );

    // 监听来自 popup 的设置更新
    chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
      if (msg && msg.type === "set_interval") {
        const ms = parseInt(msg.ms, 10);
        if (!isNaN(ms) && ms > 0) {
          startIntervalCheck(ms);
          sendResponse({ ok: true });
        } else {
          sendResponse({ ok: false, error: "invalid ms" });
        }
      }
      // 同步请求当前播放状态
      if (msg && msg.type === "query_playing") {
        sendResponse({ playing: isVideoPlaying(currentVideo) });
      }
    });

    console.log("[video-monitor] content script initialized");
  })();
})();

const btns = document.querySelectorAll(".login-warn-btns .ant-btn");
btns[0].click();
